use std::fmt::Debug;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, sqlx::Type, Serialize, Deserialize)]
// #[sqlx(type_name = "enum('build', 'setting')")]
// #[sqlx(rename_all = "lowercase")]
#[repr(i32)]
pub enum DataEnum {
    Build = 1,
    Setting = 2,
    None = 3,
}

impl From<String> for DataEnum {
    fn from(s: String) -> Self {
        match s.to_lowercase().as_str() {
            "build" => Self::Build,
            "setting" => Self::Setting,
            _ => Self::None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, sqlx::Type, Serialize, Deserialize)]
#[repr(i32)]
// #[sqlx(rename_all = "lowercase")]
pub enum DataDefault {
    Default = 1,
    Normal = 2,
}

impl From<String> for DataDefault {
    fn from(s: String) -> Self {
        match s.to_lowercase().as_str() {
            "default" => Self::Default,
            _ => Self::Normal,
        }
    }
}

#[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize)]
pub struct SimpleEntity {
    pub id: u64,
    pub data_default: DataDefault,
    pub data_enum: DataEnum,
    pub simple_name: String,
}

#[cfg(test)]
mod sqlx_test {
    use crate::sqlx::SimpleEntity;

    #[tokio::test]
    async fn sqlx_base() -> Result<(), sqlx::Error> {
        use sqlx::mysql::MySqlPoolOptions;
        let pool = MySqlPoolOptions::new().connect("mysql://root:asdqwe123@127.0.0.1:3306/sqlx_simple?useUnicode=true&characterEncoding=utf8&useOldAliasMetadataBehavior=true&autoReconnect=true&serverTimezone=Asia/Shanghai&useSSL=false").await?;

        // insert into
        //
        // let id = sqlx::query!(
        //     "insert into simple_s(data_default,data_enum,simple_name) values(?,?,?)",
        //     "normal",
        //     "setting",
        //     "first"
        // )
        // .execute(&pool)
        // .await?
        // .last_insert_id();
        //
        // println!("插入成功:id = {}", id);
        //
        // // update
        //
        // let rows_affected = sqlx::query!(
        //     "update simple_s set data_default = ? where id = ?",
        //     "default",
        //     id
        // )
        // .execute(&pool)
        // .await?
        // .rows_affected();

        // println!("修改成功:{}", rows_affected);

        // select
        //
        let entity = sqlx::query_as!(SimpleEntity, "select * from simple_s where id = ?", 1)
            .fetch_one(&pool)
            .await?;

        println!("查询出的的结果: {:#?}", entity);

        let lst = sqlx::query_builder::QueryBuilder::new(
        "select id,cast(data_default as signed) as data_default,cast(data_enum as signed) data_enum,simple_name  from simple_s where id = ",
    )
    .push_bind(5)
    .build_query_as::<SimpleEntity>()
    .fetch_all(&pool)
    .await?;

        println!("查询出的的结果: {:#?}", lst);

        Ok(())
    }
}
